package nl.hva.three2learn.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import nl.hva.three2learn.dao.CategoryDao;
import nl.hva.three2learn.exception.ResourceNotFoundException;
import nl.hva.three2learn.model.Category;
import nl.hva.three2learn.model.Course;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/category")
public final class CategoryController {

	@Autowired
	private CategoryDao categoryDao;
	
	@RequestMapping(value = "/overview_manage/{categoryId}", method = RequestMethod.GET)
	public String startManageCategory(
			HttpSession session,
			@PathVariable("categoryId") long categoryId) {
		
		session.setAttribute("category", categoryDao.findById(categoryId));
		return "category/manage_category";
	}
	
	@RequestMapping(value = "/start_add_category", method = RequestMethod.GET)
	public String startAddCategory() {
		
		return "category/add_category";
	}
	
	@RequestMapping(value = "/add_category", method = RequestMethod.POST)
	public String addCategory(
			@RequestParam("categoryName") String categoryName) {
		categoryDao.save(new Category(categoryName));
		
		return "redirect:/category/overview";
	}
	
	@RequestMapping(value = "/manage_category", method = RequestMethod.POST)
	public String manageCategory(
			@RequestParam("categoryId") long categoryId,
			@RequestParam("categoryName") String categoryName) {
		Category category = categoryDao.findById(categoryId);
		category.setName(categoryName);
		
		categoryDao.save(category);
		
		return "redirect:/category/overview_manage";
	}
	
	@RequestMapping("/overview_manage")
	public String overviewManage(Model model) {
		
		List<Category> categories = categoryDao.findAllCategories();
		
		model.addAttribute("categories", categories);
		
		return "category/overview_manage";
	}
	
	@RequestMapping("/overview")
	public String overview(Model model) {
		
		List<Category> categories = categoryDao.findAllCategories();
		
		model.addAttribute("categories", categories);
		
		return "category/overview";
	}
	
	@RequestMapping(value = "/overview/{categoryId}", method = RequestMethod.GET)
	public ModelAndView courses(@PathVariable("categoryId") long categoryId) {
		
		Category category = categoryDao.findById(categoryId);
		
		if (category == null)
			throw new ResourceNotFoundException();
		
		List<Course> courses = category.getCourses();
		
		ModelAndView modelAndView = new ModelAndView("category/courses");
		modelAndView.addObject("category", category);
		modelAndView.addObject("courses", courses);
		
		return modelAndView;
	}
}
